package com.my.oschina.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.CheckBox;
import android.widget.EditText;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.my.oschina.R;
import com.my.oschina.api.ApiClient;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.Result;
import com.my.oschina.bean.User;
import com.my.oschina.common.StringUtils;
import com.my.oschina.common.UIHelper;

/**
 * 登录
 * 
 * @author XuShaoJie
 * @version 2013-04-15
 */
public class LoginActivity extends SherlockActivity {

	private EditText accountEdit;
	private EditText passwordEdit;
	private CheckBox checkBox;// 记住用户名
	private ProgressDialog mProgressDialog;
	private boolean cancelable = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle(R.string.login);

		initLoginInfo();
	}

	/**
	 * 初始化登录信息
	 */
	private void initLoginInfo() {
		accountEdit = (EditText) findViewById(R.id.login_user_edit);
		passwordEdit = (EditText) findViewById(R.id.login_pwd_edit);
		checkBox = (CheckBox) findViewById(R.id.login_remember_me);
		checkBox.setChecked(true);

		// 是否显示登录信息
		AppContext ac = (AppContext) getApplication();
		User user = ac.getLoginInfo();
		if (user == null || !user.isRememberMe()) {
			return;
		}
		if (!StringUtils.isEmpty(user.getAccount())) {
			accountEdit.setText(user.getAccount());
			checkBox.setChecked(user.isRememberMe());
		}
		if (!StringUtils.isEmpty(user.getPwd())) {
			passwordEdit.setText(user.getPwd());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		// 返回
		case android.R.id.home:
			finish();
			break;
		// 登录
		case R.id.menu_login_btn:
			checkLogin();
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * 登录
	 */
	private void checkLogin() {
		String account = accountEdit.getText().toString();
		String pwd = passwordEdit.getText().toString();
		// 判断输入
		if (StringUtils.isEmpty(account)) {
			UIHelper.ToastMessage(this,
					getString(R.string.msg_login_email_null));
			return;
		}
		if (StringUtils.isEmpty(pwd)) {
			UIHelper.ToastMessage(this, getString(R.string.msg_login_pwd_null));
			return;
		}
		OnCancelListener cancelListener = new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialogInterface) {
				// 正在登录的时候按下返回键的处理
			}
		};
		mProgressDialog = ProgressDialog.show(this, getString(R.string.tips),
				getString(R.string.login_loading), true,
				LoginActivity.this.cancelable, cancelListener);
		mProgressDialog.setCanceledOnTouchOutside(false);
		
		login(account, pwd, true);

	}

	// TODO 在gprs网络的时候，多次点击，会出现问题
	/**
	 * 登录验证
	 * 
	 * @param account
	 * @param pwd
	 * @param isRememberMe
	 */
	private void login(final String account, final String pwd,
			final boolean isRememberMe) {
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				mProgressDialog.dismiss();
				// 登录成功
				if (msg.what == 1) {
					User user = (User) msg.obj;
					if (user != null) {
						// 清空原先cookie
						ApiClient.cleanCookie();
						// TODO 发送通知广播
						// UIHelper.sendBroadCast(LoginActivity.this,
						// user.getNotice());
						UIHelper.ToastMessage(LoginActivity.this,
								R.string.msg_login_success);
						Intent intent = new Intent(LoginActivity.this,
								UserInfoActivity.class);
						startActivity(intent);
						LoginActivity.this.finish();
					}
				}
				// 账户或者密码错误
				else if (msg.what == 0) {
					UIHelper.ToastMessage(LoginActivity.this,
							getString(R.string.msg_login_fail) + msg.obj);
				}
				// 其它异常
				else if (msg.what == -1) {
					((AppException) msg.obj).makeToast(LoginActivity.this);
				}
			}
		};
		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				try {
					AppContext ac = (AppContext) getApplication();
					User user = ac.loginVerify(account, pwd);
					user.setAccount(account);
					user.setPwd(pwd);
					user.setRememberMe(isRememberMe);
					Result res = user.getValidate();
					if (res.OK()) {
						ac.saveLoginInfo(user);// 保存登录信息
						msg.what = 1;// 成功
						msg.obj = user;
					} else {
						ac.cleanLoginInfo();// 清除登录信息
						msg.what = 0;// 失败
						msg.obj = res.getErrorMessage();
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

}
